package com.waterms.action.admin;

import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.aspectj.util.FileUtil;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.waterms.model.File;
import com.waterms.service.FileService;
import com.waterms.util.Pagination;

public class FileAction extends ActionSupport{
	private FileService fileService;
	private List<File> files;
	private File file;
	private Pagination page;
	private java.io.File newFile;
	private String newFileFileName;
	private String newFileContentType;
	
	@Override
	public String execute()
	{
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put("current", "fileManage");
		return SUCCESS;
	}
	
	public String list()
	{
		if (page == null)
		{
			page = new Pagination();
		}
		
		files = fileService.list(page);
		return SUCCESS;
	}
	
	public String add()
	{
		file = new File();
		String destFileName = System.currentTimeMillis() + newFileFileName;
		file.setFileName(newFileFileName);
		
		String upload = ServletActionContext.getServletContext()
				.getRealPath(File.UPLOAD_DIR);
		java.io.File uploadDir = new java.io.File(upload);
		if (!uploadDir.exists())
		{
			uploadDir.mkdir();
		}
		
		java.io.File targetFile = new java.io.File(upload + "\\" + destFileName);
		
		try
		{
			FileUtil.copyFile(newFile, targetFile);
			newFile.deleteOnExit();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		
		file.setPath(File.UPLOAD_DIR + "\\" + destFileName);
		fileService.add(file);
		return SUCCESS;
		
	}
	
	public String delete()
	{
		fileService.delete(file);
		return SUCCESS;
	}
	
	

	public FileService getFileService() {
		return fileService;
	}

	public void setFileService(FileService fileService) {
		this.fileService = fileService;
	}

	public List<File> getFiles() {
		return files;
	}

	public void setFiles(List<File> files) {
		this.files = files;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public Pagination getPage() {
		return page;
	}

	public void setPage(Pagination page) {
		this.page = page;
	}

	public java.io.File getNewFile() {
		return newFile;
	}

	public void setNewFile(java.io.File newFile) {
		this.newFile = newFile;
	}

	public String getNewFileFileName() {
		return newFileFileName;
	}

	public void setNewFileFileName(String newFileFileName) {
		this.newFileFileName = newFileFileName;
	}

	public String getNewFileContentType() {
		return newFileContentType;
	}

	public void setNewFileContentType(String newFileContentType) {
		this.newFileContentType = newFileContentType;
	}
	
	
	

}
